package org.springxrsk.modules.auth.service;

import lombok.RequiredArgsConstructor;
import org.springxrsk.core.oauth2.provider.OAuth2Request;
import org.springxrsk.core.oauth2.service.OAuth2User;
import org.springxrsk.core.oauth2.service.OAuth2UserService;
import org.springxrsk.core.tool.utils.Func;
import org.springxrsk.core.tool.utils.StringUtil;
import org.springxrsk.modules.auth.provider.UserType;
import org.springxrsk.modules.auth.utils.TokenUtil;
import org.springxrsk.modules.system.pojo.entity.UserInfo;
import org.springxrsk.modules.system.service.IUserService;

import java.util.Optional;

/**
 * BladeUserDetailService
 *
 * @author
 */
@RequiredArgsConstructor
public class XrskUserDetailService implements OAuth2UserService {
	private final IUserService userService;

	@Override
	public OAuth2User loadByUserId(String userId, OAuth2Request request) {
		// 获取用户参数
		String userType = Optional.ofNullable(request.getUserType())
			.filter(s -> !StringUtil.isBlank(s))
			.orElse(UserType.WEB.getName());

		// 获取用户信息
		UserInfo userInfo = userService.userInfo(Func.toLong(userId), UserType.of(userType));

		// 构建oauth2用户信息
		return TokenUtil.convertUser(userInfo, request);
	}

	@Override
	public OAuth2User loadByUsername(String username, OAuth2Request request) {
		// 获取用户参数
		String userType = Optional.ofNullable(request.getUserType())
			.filter(s -> !StringUtil.isBlank(s))
			.orElse(UserType.WEB.getName());


//		String tenantId = request.getTenantId();

//		// 获取用户信息
//		UserInfo userInfo = userService.userInfo(tenantId, username, UserType.of(userType));
		// 获取用户信息账户
		UserInfo userInfo = userService.userInfo(username, UserType.of(userType));

		// 构建oauth2用户信息
		return TokenUtil.convertUser(userInfo, request);
	}

	@Override
	public boolean validateUser(OAuth2User user) {
		return Optional.ofNullable(user)
			.filter(u -> u.getUserId() != null && !u.getUserId().isEmpty()) // 检查userId不为空
			.filter(u -> u.getAuthorities() != null && !u.getAuthorities().isEmpty()) // 检查authorities不为空
			.isPresent(); // 如果上述条件都满足，则返回true，否则返回false
	}

}
